/**
 * @Description: 左旋转字符串
 * 字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。
 * 请定义一个函数实现字符串左旋转操作的功能。
 * 比如，输入字符串"abcdefg"和数字2，
 * 该函数将返回左旋转两位得到的结果"cdefgab"。
 * @Date:Create in 15:21  2022/7/8
 */
public class reverseLeftWords_offer_58 {

    public static void main(String[] args) {
        String s = "lrloseumgh";
        int k = 6;
        System.out.println(reverseLeftWords2(s, k));
    }

    //运用额外空间
    public static String reverseLeftWords1(String s, int n) {
        char[] ch1 = s.toCharArray();
        int size = s.length();
        char[] ch2 = new char[size];
        int i = 0, j = 0,a=n;
        while (a < size) {
            ch2[i] = ch1[a];
            i++;
            a++;
        }

        while (j < n) {
//            System.out.println(i + " " + j);
//            System.out.println(j);
            ch2[i] = ch1[j];
            i++;
            j++;
        }
        return new String(ch2);
    }

    /**
     * 不运用额外空间
     *
     * 反转区间为前n的子串
     * 反转区间为n到末尾的子串
     * 反转整个字符串
     */
    public static String reverseLeftWords2(String s, int n) {
        int len = s.length();
        StringBuilder sb = new StringBuilder(s);
        reverseString(sb,0,n-1);
        reverseString(sb,n,len-1);
        reverseString(sb,0,len-1);
        return sb.toString();
    }

    public static void reverseString(StringBuilder sb,int start,int end){
        while(start < end){
            char temp = sb.charAt(start);
            sb.setCharAt(start, sb.charAt(end));
            sb.setCharAt(end, temp);
            start++;
            end--;
        }
    }
}
